package com.lyb.server.hb.utils;


import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.KeyFactory;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * RSA 签名加解密工具类 支持openssl
 */
public class RSAUtil {

    private static final String DEFAULT_SYSTEM_ENCODING = "UTF-8";// 默认编码

    /**
     * RSA公钥加密
     *
     * @param str
     *            加密字符串
     * @param publicKey
     *            公钥
     * @return 密文
     * @throws Exception
     *             加密过程中的异常信息
     */
    public static String encrypt( String str, String publicKey ) throws Exception{
        //分段加密
        byte[] decoded = Base64.decodeBase64(publicKey);
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        byte[] bytes = str.getBytes();
        int inputLen = bytes.length;
        int offLen = 0;//偏移量
        int i = 0;
        ByteArrayOutputStream bops = new ByteArrayOutputStream();
        while(inputLen - offLen > 0){
            byte [] cache;
            if(inputLen - offLen > 117){
                cache = cipher.doFinal(bytes, offLen,117);
            }else{
                cache = cipher.doFinal(bytes, offLen,inputLen - offLen);
            }
            bops.write(cache);
            i++;
            offLen = 117 * i;
        }
        bops.close();
        byte[] encryptedData = bops.toByteArray();
        String encodeToString = Base64.encodeBase64String(encryptedData);
        return encodeToString;

    }

    /**
     * RSA私钥解密
     *
     * @param str
     *            加密字符串
     * @param privateKey
     *            私钥
     * @return 铭文
     * @throws Exception
     *             解密过程中的异常信息
     */
    public static String decrypt(String str, String privateKey) throws Exception{
        //分段解密
        byte[] decoded = Base64.decodeBase64(privateKey);
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, priKey);

        byte[] bytes = Base64.decodeBase64(str);
        int inputLen = bytes.length;
        int offLen = 0;
        int i = 0;
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        while(inputLen - offLen > 0){
            byte[] cache;
            if(inputLen - offLen > 128){
                cache = cipher.doFinal(bytes,offLen,128);
            }else{
                cache = cipher.doFinal(bytes,offLen,inputLen - offLen);
            }
            byteArrayOutputStream.write(cache);
            i++;
            offLen = 128 * i;

        }
        byteArrayOutputStream.close();
        return byteArrayOutputStream.toString();
    }

    /**
     * body 签名
     * @param signBody 签名内容
     * @param privateKey 私钥
     * @return
     */
    public static String sign(String signBody, String privateKey) throws Exception {
        String sign = "";
        try {
            RSAHelper rsaHelper = new RSAHelper();
            rsaHelper.initKey(privateKey, null);

            sign = new String(rsaHelper.signRSA(signBody.getBytes(DEFAULT_SYSTEM_ENCODING), true,
                    DEFAULT_SYSTEM_ENCODING), DEFAULT_SYSTEM_ENCODING);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sign;
    }


    /**
     * body 验签
     * @param signBody 签名内容
     * @param sign 签名
     * @param publicKey 公钥
     * @return
     */
    public static boolean verifySign(String signBody, String sign, String publicKey) throws Exception {
        boolean verifySign = false;
        try {
            RSAHelper rsaHelper = new RSAHelper();
            rsaHelper.initKey(null, publicKey);

            verifySign = rsaHelper.verifyRSA(signBody.getBytes(DEFAULT_SYSTEM_ENCODING),
                    sign.getBytes(DEFAULT_SYSTEM_ENCODING), true, DEFAULT_SYSTEM_ENCODING);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return verifySign;
    }
}

